﻿#include "BaseShader.h"

BaseShader::BaseShader(QObject* parent)
	: QObject(parent)
{

}

void BaseShader::InitShaderSource(QString& vertexSource, QString& fragmentSource)
{
	this->vertexSource = vertexSource;
	this->fragmentSource = fragmentSource;
}
bool BaseShader::Create(std::function<void(int vertexIn_position, int textureIn_position, GLfloat ver[8], GLfloat tex[8])> func)
{
	if (!program.isLinked())
	{
		if (!program.addShaderFromSourceCode(QOpenGLShader::Vertex, vertexSource)) {
			qDebug() << "Vertex shader error:" << program.log();
			return false;
		}


		if (!program.addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentSource)) {
			qDebug() << "Fragment shader error:" << program.log();
			return false;
		}

		//设置顶点坐标的变量
		program.bindAttributeLocation("vertexIn", vertexIn_position);

		//设置材质坐标
		program.bindAttributeLocation("textureIn", textureIn_position);

		if (!program.link()) {
			qDebug() << "Shader link error:" << program.log();
			return false;
		}
	}
	if (!program.bind())
	{
		qDebug() << "Shader bind error:" << program.log();
		return false;
	}

	//启用顶点及材质坐标
	func(vertexIn_position, textureIn_position, ver, tex);
	//从shader获取材质
	unis[0] = program.uniformLocation("tex_y");
	unis[1] = program.uniformLocation("tex_u");
	unis[2] = program.uniformLocation("tex_v");
	return true;
}

void BaseShader::Release()
{
	program.release();
}

BaseShader::~BaseShader()
{

}
